import React, {
    Component
} from 'react'
import {
    Link
} from 'react-router'
import {
    R_header_fixed
} from './common/index'
import {
    Toast,
    HttpService
} from '../Http'
import WxServer from '../wx/WxServer'

import imgCard1 from '../img/card/1.png'
import imgCard2 from '../img/card/2.png'
import imgCard3 from '../img/card/3.png'

export default class BuyDevice extends Component {
    constructor(props) {
        super(props);
        this.state = {
            first: 1,
            second: 0,
            third: 0,
            total: 0,
            address: '',
            phone: 0,
            recivername: '',
            smartcard: '',
            whitecard: '',
            whitecard13_56: ''
        }

    }
    componentWillMount() {
        if (localStorage.buydevice) {
            const buydevice = localStorage.buydevice.split(',');
            if (this.props.params.shengji == 'true') {
                buydevice[1] = 0;
                buydevice[2] = 0;
            }
            //const price = buydevice[0] * this.state.smartcard + buydevice[1] * this.state.whitecard + buydevice[2] * this.state.whitecard13_56;
            this.setState({
                first: buydevice[0],
                second: buydevice[1],
                third: buydevice[2]
            })
        }
        //获取设备价格
        HttpService.query({
            url: '/app/device/getPrices',
            sync: false,
            data: {
                token: localStorage.appToken
            },
            success: (res => {
                const {
                    smartcard,
                    whitecard,
                    whitecard13_56
                } = res.data
                this.setState({
                    smartcard: smartcard.toFixed(2),
                    whitecard: whitecard.toFixed(2),
                    whitecard13_56: whitecard13_56.toFixed(2)
                })
            })
        })

        //获取收货地址
        HttpService.query({
            url: '/app/user/getUserinfo',
            sync: false,
            data: {
                token: localStorage.appToken,
                babyid: localStorage.babyid
            },
            success: (res => {
                let address = '[无收货地址..]'
                if (res.data.deliveryaddr != null) {
                    address = res.data.province + res.data.city + res.data.town
                }
                this.setState({
                    address,
                    deliveryaddr: res.data.deliveryaddr || '',
                    phone: res.data.telephone,
                    recivername: res.data.recivername || '[无收货人]'
                })
            })
        });
    }
    /**
     * buydevice 是否有值--没有则默认
     * map页面加载完后--加载百度统计点击事件
     */
    componentDidMount() {

        let from = '购买设备';
        if (this.props.params.shengji == 'true')
            from += '<-升级设备';
        _hmt.push(['_trackEvent', 'page', 'buydevice', from]);
        this.totalPrice();
        setTimeout(() => {
            this.totalPrice();
        }, 1000)
    }

    componentWillUnmount() {
        localStorage.buydevice = this.state.first + ',' + this.state.second + ',' + this.state.third;
    }

    totalPrice() {
        const {
            first,
            second,
            third,
            smartcard,
            whitecard,
            whitecard13_56
        } = this.state
        let price = first * smartcard + second * whitecard + third * whitecard13_56
        this.setState({
            total: price.toFixed(2)
        })
    }

    numHandle(name, obj) {
        let data = {};
        if (obj.currentTarget.className == 'add') {
            data[name] = ++this.state[name];
        } else {
            if (this.state[name] == 0)
                return;
            data[name] = --this.state[name];
        }
        this.setState(data);
        this.totalPrice();
    }
    buySubmit(e) {
        e.preventDefault();
        if (parseInt(this.state.total) == 0) {
            Toast.toast('请至少选择一个设备')
            return;
        }
        if (!/micromessenger/.test(navigator.userAgent.toLowerCase())) {
            Toast.toast('在微信端登录方可支付')
            return;
        }
        if (this.state.recivername == '[无收货人]' || this.state.deliveryaddr == '') {
            Toast.toast('请完善收货地址信息');
            return;
        }
        if (this.state.total == 0) {
            Toast.toast('请至少选择一个设备');
            return;
        }
        const {
            first,
            second,
            third,
            smartcard,
            whitecard,
            whitecard13_56
        } = this.state
        let data = ''; //格式：设备类型(123),设备价格,数量|设备类型,设备价格,数量
        if (first > 0) {
            data += '2,' + parseInt(smartcard) + ',' + first + '|'
        }
        if (second > 0) {
            data += '3,' + parseInt(whitecard) + ',' + second + '|'
        }
        if (third > 0) {
            data += '13_56,' + parseInt(whitecard13_56) + ',' + third + '|'
        }
        let clkbuy = '立即购买';
        if (this.props.params.shengji == 'true') {
            clkbuy = '立即购买-升级';
        }
        //什么入口进入立即购买页面--添加百度统计点击事件
        _hmt.push(['_trackEvent', 'page', 'BuyDevice', clkbuy]);

        HttpService.query({
            url: '/app/device/purchase',
            sync: false,
            data: {
                token: localStorage.appToken,
                babyid: localStorage.babyid,
                data: data.slice(0, -1),
                source: 'H5',
                weixinclient: true
            },
            success: (res => {
                if (res.code == 10134) {
                    _hmt.push(['_trackEvent', 'page', 'buydevice', '购买设备[提交操作]']);
                    WxServer.weChatPay(res, (response) => {
                        if (response.err_msg == "get_brand_wcpay_request:ok") {
                            _hmt.push(['_trackEvent', 'page', 'BuyDevice', '购买设备成功']);
                            Toast.toast('支付成功');
                        } else if (response.err_msg == "get_brand_wcpay_request:cancel") {
                            Toast.toast('支付取消')
                        } else {
                            Toast.toast('支付失败')
                        }
                    })
                } else {
                    Toast.toast(res.msg);
                }
            })
        })

    }
    buysbmtno(e) {
        e.preventDefault();
    }

    render() {
        const {
            first,
            second,
            third,
            total,
            address,
            phone,
            recivername,
            deliveryaddr,
            smartcard,
            whitecard,
            whitecard13_56
        } = this.state
        return (
            <form className='buybox' onSubmit={this.buysbmtno.bind(this)}>
                <R_header_fixed left="1" title="购买设备"/>
                <Link to={'/Address/' + this.props.params.shengji} className='buyinfo'>
                    <h5>收货人信息</h5>
                    <div className='aduser'>
                        <span>{recivername || ''}</span>
                        <span>{phone || ''}</span>
                    </div>
                    <p className='adcity'>{address + deliveryaddr}</p>
                    <span className='adstatus'>编辑</span>
                </Link>
                <ul className='buylist'>
                    <li>
                        <img src={imgCard3}/>
                        <h4>智能学生证</h4>
                        <h5>价格：{smartcard}</h5>
                        <div className='intro'>
                            实时定位，亲情通话，宝宝更安全
                            <p className='btns'>
                                <button className='del' onClick={this.numHandle.bind(this, 'first')}/>
                                <span>{first}</span>
                                <button className='add' onClick={this.numHandle.bind(this, 'first')}/>
                            </p>
                        </div>
                    </li>
                    {this.props.params.shengji == 'true'
                        ? ''
                        : <li>
                            <img src={imgCard1}/>

                            <h4>2.4G考勤卡</h4>
                            <h5>价格：{whitecard}</h5>
                            <div className='intro'>
                                建议购买前咨询客服，确认孩子所在学校所使用的考勤卡类型
                                <p className='btns'>
                                    <button className='del' onClick={this.numHandle.bind(this, 'second')}/>
                                    <span>{second}</span>
                                    <button className='add' onClick={this.numHandle.bind(this, 'second')}/>
                                </p>
                            </div>
                        </li>}

                    {this.props.params.shengji == 'true'
                        ? ''
                        : <li>
                            <img src={imgCard2}/>
                            <h4>
                                13.56 G考勤卡
                            </h4>
                            <h5>价格：{whitecard13_56}</h5 >
                            <div className='intro'>
                                建议购买前咨询客服，确认孩子所在学校所使用的考勤卡类型
                                <p className='btns'>
                                    <button className='del' onClick={this.numHandle.bind(this, 'third')}/>
                                    <span>{third}</span>
                                    <button className='add' onClick={this.numHandle.bind(this, 'third')}/>
                                </p>
                            </div>
                        </li>
}
                </ul>
                {total == '0.00'
                    ? ''
                    : <div className='smtbox'>
                        总价：<span>{total}</span>
                        <button onClick={this.buySubmit.bind(this)} className="tgGoBal">去结算</button>
                    </div>}
            </form>
        )
    }
}
